package com.gang.music.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gang.music.common.AjaxResult;
import com.gang.music.common.RegisterStatistics;
import com.gang.music.core.toolbox.kit.DateKit;
import com.gang.music.system.entity.PlayRecord;
import com.gang.music.system.service.PlayRecordService;
import com.gang.music.system.service.UserService;
import com.smallchill.core.toolbox.Paras;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * echarts图表显示
 *
 */

@Controller
@RequestMapping("/statistics")
public class StatisticsDayController extends BaseController{
	
	@Autowired
	private PlayRecordService playRecordService;
	@Autowired
	private UserService userService;
	
	@RequestMapping("/detailajax")
	@ResponseBody
	public AjaxResult getDetailAjax(HttpServletRequest request, @RequestParam int days){
		
		Paras paras = Paras.create();
		Date currDate = DateKit.getDate();
		Date daysBreforeDate = DateKit.offsiteDay(currDate, -(days-1));
		
		String updateTime = DateKit.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		String[] showDate = new String[days];
		Long[] playAmout = new Long[days];
		Long[] registerAmout = new Long[days];
		
		EntityWrapper<PlayRecord> pew = new EntityWrapper<>();
		pew.between("play_date", daysBreforeDate, currDate).orderBy("play_date", true);
		List<PlayRecord> playRecords = playRecordService.selectList(pew);
		
		List<RegisterStatistics> registerStatisticsList = userService.findRegisterStatistics(daysBreforeDate, currDate);
		
		Date offsiteDate = null;
		for(int i = 0; i < days; i++) {
			
			offsiteDate = DateKit.offsiteDay(daysBreforeDate, +i);
			showDate[i] = DateKit.format(offsiteDate, "MM月dd");
			for (PlayRecord playRecord : playRecords) {
				if(DateKit.equalsDate(playRecord.getPlayDate(), offsiteDate)) {
					playAmout[i] = playRecord.getPlayCount();
					break;
				}
			}
			playAmout[i] = playAmout[i] == null ? 0l : playAmout[i];
			
			for (RegisterStatistics registerStatistics : registerStatisticsList) {
				if(DateKit.equalsDate(registerStatistics.getDate(), offsiteDate)) {
					registerAmout[i] = registerStatistics.getCount();
					break;
				}
			}
			registerAmout[i] = registerAmout[i] == null ? 0l : registerAmout[i];
		}
		paras.put("updateTime", updateTime);
		paras.put("showDate", showDate);
		paras.put("playAmout", playAmout);
		paras.put("registerAmout", registerAmout);
		
		return success(paras);
	}
	
}
